package com.maodou.android.ui.page.home

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.Email
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.maodou.android.R
import com.maodou.android.ui.page.CategoryKey
import com.maodou.android.ui.page.ContactKey
import com.maodou.android.ui.page.EditAccountKey
import com.maodou.android.ui.page.LoginKey
import com.maodou.android.ui.page.WebViewKey
import com.maodou.android.viewmodel.account.AccountViewModel
import com.maodou.core.navigation.GlobalUiBus
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.AppDivider
import com.maodou.core.ui.components.AppText
import com.maodou.core.ui.components.TitleText
import com.maodou.core.ui.components.VSpacer
import com.maodou.core.ui.components.debouncedClickable
import com.maodou.core.ui.components.rememberDialogState
import com.maodou.core.utils.toastOnUi
import kotlinx.coroutines.launch

/**
 * @Author Xing
 * @CreateTime 2025年09月17日
 * @Description 首页抽屉UI（按原型图实现）
 */
@Composable
fun HomeDrawerUI(
    drawerState: DrawerState,
    onLogout: () -> Unit = {},
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val dialog = rememberDialogState()

    ModalDrawerSheet {
        Column(
            modifier = Modifier
                .fillMaxHeight()
                .padding(vertical = 12.dp),
            horizontalAlignment = Alignment.Start
        ) {
            VSpacer(12.dp)
            TitleText(
                text = "毛豆工具箱",
                modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp)
            )
            AppText(
                text = "abc123@163.com",
                modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp)
            )
            VSpacer(12.dp)
            AppDivider()
            // 菜单项
            NavigationDrawerItem(
                icon = { Icon(imageVector = Icons.Outlined.Add, contentDescription = null) },
                label = { Text("添加账号") },
                selected = false,
                onClick = {
                    scope.launch { drawerState.close() }
                    Navigator3.navigate(EditAccountKey())
                },
                modifier = Modifier.padding(horizontal = 8.dp)
            )
            NavigationDrawerItem(
                icon = { Icon(imageVector = Icons.Outlined.Email, contentDescription = null) },
                label = { Text("分类管理") },
                selected = false,
                onClick = {
                    scope.launch { drawerState.close() }
                    Navigator3.navigate(CategoryKey)
                },
                modifier = Modifier.padding(horizontal = 8.dp)
            )
            NavigationDrawerItem(
                icon = { Icon(imageVector = Icons.Outlined.Refresh, contentDescription = null) },
                label = { Text("检查更新") },
                selected = false,
                onClick = {
                    scope.launch { drawerState.close() }
                    context.toastOnUi("检查更新")
                },
                modifier = Modifier.padding(horizontal = 8.dp)
            )
            NavigationDrawerItem(
                icon = { Icon(imageVector = Icons.Outlined.Email, contentDescription = null) },
                label = { Text("使用帮助") },
                selected = false,
                onClick = {
                    scope.launch { drawerState.close() }
                    Navigator3.navigate(WebViewKey("https://blog.md888.cc/posts/chrome-fb-cookie/"))
                },
                modifier = Modifier.padding(horizontal = 8.dp)
            )
            NavigationDrawerItem(
                icon = { Icon(imageVector = Icons.Outlined.Email, contentDescription = null) },
                label = { Text("联系我们") },
                selected = false,
                onClick = {
                    scope.launch { drawerState.close() }
                    Navigator3.navigate(ContactKey)
                },
                modifier = Modifier.padding(horizontal = 8.dp)
            )

            Spacer(modifier = Modifier.weight(1f))

            // 退出登录 按钮（绿色描边，圆角胶囊）
            OutlinedButton(
                onClick = {
                    scope.launch { drawerState.close() }
                    dialog.show(
                        title = "是否退出登录",
//                        content = if(current.title == null) null else current.message,
                        okText = "确认退出",
                        onOk = {
                            Navigator3.resetTo(LoginKey)
                            onLogout()
                        }
                    )
                },
                shape = RoundedCornerShape(24.dp),
                border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary),
                colors = ButtonDefaults.outlinedButtonColors(
                    contentColor = MaterialTheme.colorScheme.primary
                ),
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 24.dp)
                    .height(44.dp)
            ) {
                Text(text = "退出登录")
            }

            Spacer(Modifier.height(8.dp))

            // 版本号
            AppText(
                text = "v1.0.0",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.outline,
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
                    .padding(bottom = 8.dp)
            )
        }
    }
}

/**
 * 账号筛选底部弹窗
 */
@Composable
fun AccountFilterBottomSheet(
    viewModel: AccountViewModel,
    onDismiss: () -> Unit? = {},
    onConfirm: (platforms: Set<String>, statuses: Set<String>, tags: Set<String>) -> Unit = { _, _, _ -> }
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    // 筛选状态
    var selectedPlatforms by remember { mutableStateOf(uiState.accountFilterParams?.platforms ?: setOf()) }
    var selectedStatuses by remember { mutableStateOf(uiState.accountFilterParams?.statuses ?: setOf()) }
    var selectedTags by remember { mutableStateOf(uiState.accountFilterParams?.tags ?: setOf()) }

    val platforms = listOf("Facebook", "Instagram")

    val statuses = listOf("待检测", "存活中", "被封禁")

    val tags = listOf("2FA","Cookie", "密码", "手机号", "代理", "邮箱", "邮箱密码", "IP/国家")

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White)
            .padding(16.dp).debouncedClickable {  }
    ) {

        Row(
            modifier = Modifier.padding(bottom = 16.dp).fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            AppText(
                text = "账号筛选",
                style = TextStyle(
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                )
            )

            Icon(
                imageVector = Icons.Default.Clear,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.size(24.dp).debouncedClickable { onDismiss() }
            )
        }

        // 平台选择
        FilterSection(
            title = "平台",
            options = platforms,
            selectedOptions = selectedPlatforms,
            onSelectionChange = { selectedPlatforms = it }
        )

        VSpacer(16.dp)

        // 存活状态选择
        FilterSection(
            title = "存活状态",
            options = statuses,
            selectedOptions = selectedStatuses,
            onSelectionChange = { selectedStatuses = it }
        )

        VSpacer(16.dp)

        // 账号标签选择
        FilterSection(
            title = "账号标签",
            options = tags,
            selectedOptions = selectedTags,
            onSelectionChange = { selectedTags = it }
        )

        VSpacer(32.dp)

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            OutlinedButton(
                onClick = {
                    selectedPlatforms = setOf()
                    selectedStatuses = setOf()
                    selectedTags = setOf()
                },
                modifier = Modifier.weight(1f),
                colors = ButtonDefaults.outlinedButtonColors(
                    contentColor = MaterialTheme.colorScheme.outline
                )
            ) {
                Text("重置")
            }

            Button(
                onClick = {
                    onConfirm(selectedPlatforms, selectedStatuses, selectedTags)
                },
                modifier = Modifier.weight(1f),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFF007AFF)
                )
            ) {
                Text("确认", color = Color.White)
            }
        }
    }
}

/**
 * 筛选区域组件
 */
@Composable
private fun FilterSection(
    title: String,
    options: List<String>,
    selectedOptions: Set<String>,
    onSelectionChange: (Set<String>) -> Unit
) {
    Column {
        Text(
            text = title,
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.onSurface,
            modifier = Modifier.padding(bottom = 8.dp)
        )

        FlowRow(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            options.forEach { option ->
                FilterChip(
                    option = option,
                    isSelected = selectedOptions.contains(option),
                    onToggle = {
                        val newSelection = if (selectedOptions.contains(option)) {
                            selectedOptions - option
                        } else {
                            selectedOptions + option
                        }
                        onSelectionChange(newSelection)
                    }
                )
            }
        }

//        LazyRow(
//            horizontalArrangement = Arrangement.spacedBy(8.dp)
//        ) {
//            items(options) { option ->
//                FilterChip(
//                    option = option,
//                    isSelected = selectedOptions.contains(option),
//                    onToggle = {
//                        val newSelection = if (selectedOptions.contains(option)) {
//                            selectedOptions - option
//                        } else {
//                            selectedOptions + option
//                        }
//                        onSelectionChange(newSelection)
//                    }
//                )
//            }
//        }
    }
}

/**
 * 筛选标签组件
 */
@Composable
private fun FilterChip(
    option: String,
    isSelected: Boolean,
    onToggle: () -> Unit
) {
    Box(
        modifier = Modifier
            .clip(RoundedCornerShape(16.dp))
            .background(
                if (isSelected) Color(0xFF007AFF) else MaterialTheme.colorScheme.surfaceVariant
            )
            .clickable { onToggle() }
            .padding(horizontal = 12.dp, vertical = 6.dp)
    ) {
        Text(
            text = option,
            fontSize = 12.sp,
            lineHeight = 16.sp,
            color = if (isSelected) Color.White else MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Preview
@Composable
fun HomeDrawerUIPreview(){
    HomeDrawerUI(rememberDrawerState(DrawerValue.Closed))
}

@Preview
@Composable
fun AccountFilterBottomSheetPreview() {
    AccountFilterBottomSheet(hiltViewModel())
}